<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" class="queryForms">
			<el-form-item label="返修任务单" prop="repairNumber">
				<el-input v-model="queryParams.repairNumber" placeholder="请输入返修任务单" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="编号" prop="recordNumber">
				<el-input v-model="queryParams.recordNumber" placeholder="请输入编号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="合格接收人" prop="qualifiedName">
				<el-input v-model="queryParams.qualifiedName" placeholder="请输入接收人" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="零件组名称" prop="partName">
				<el-input v-model="queryParams.partName" placeholder="请输入零件组名称" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="零件组图号" prop="partFigure">
				<el-input v-model="queryParams.partFigure" placeholder="请输入零件组图号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="生产批次" prop="productionBatch">
				<el-input v-model="queryParams.productionBatch" placeholder="请输入生产批次" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="送检时间" prop="inspectDate">
				<el-date-picker v-model="queryParams.inspectDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期"> </el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<!-- 返修领料列表也没有下发 -->
			<!-- <el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleDown" v-hasPermi="['synthesize:store:sinspectlist:issue']">下发</el-button>
			</el-col> -->
			<right-toolbar menuNames="sinspectlist60" @changeTableData="changeTableData" :showSearch.sync="showSearch" @queryTable="handleQuery" :columns.sync="columns" perm="synthesize:store:sinspectlist:index"></right-toolbar>
		</el-row>

		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''" class="informationTab" ref="eleTab">
			<!-- -->
			<el-table
				:key="treetablekey"
				@expand-change="handleExpandChange"
				lazy
				:load="loadListDes"
				:row-class-name="row_class_name"
				@mousedown.native="mousedownTable"
				@row-click="row_click"
				@cell-mouse-enter="cell_mouse_enter"
				@cell-mouse-leave="cell_mouse_leave"
				@mouseup.native="mouseupTable"
				@mouseleave.native="mouseupTable"
				ref="table"
				v-loading="loading"
				:data="EntrancelistList"
				@selection-change="handleSelectionChange"
				row-key="id"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				border
				height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					           <template slot-scope="scope">
						               
						<div>{{ scope.row.sort }}</div>
						           </template
					>
					       
				</el-table-column>

				<el-table-column label="编号" prop="recordNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[0].visible" />
				<!-- <el-table-column label="编号" prop="serialNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[1].visible" /> -->
				<el-table-column label="供方" prop="supplier" min-width="150" :show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="返修任务单" prop="repairNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="状态" align="center" prop="inspectStatus" min-width="150" :show-overflow-tooltip="true" v-if="columns[14].visible">
					<template slot-scope="scope">
						<!-- <dict-tag :options="dict.type.inspect_status" :value="scope.row.inspectStatus" /> -->

						<el-tag type="warning" v-if="scope.row.inspectStatus == '0' || scope.row.inspectStatus == '1' || scope.row.inspectStatus == '7'">{{ scope.row.inspectStatus == "0" ? "待入库" : scope.row.inspectStatus == "1" ? "已入库" : "待质检" }}</el-tag>
						<el-tag type="success" v-if="scope.row.inspectStatus == '3' || scope.row.inspectStatus == '5' || scope.row.inspectStatus == '6'">{{ scope.row.inspectStatus == "3" ? "合格" : scope.row.inspectStatus == "5" ? "让步接收" : "已下发" }}</el-tag>
						<el-tag type="danger" v-if="scope.row.inspectStatus == '2' || scope.row.inspectStatus == '4'">{{ scope.row.inspectStatus == "2" ? "退货" : "不合格" }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="送检时间" prop="inspectDate" min-width="150" :show-overflow-tooltip="true" v-if="columns[4].visible" />
				<el-table-column label="工艺通知单" prop="processNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[5].visible" />
				<el-table-column label="生产批次(3B)" prop="productionBatch" min-width="150" :show-overflow-tooltip="true" v-if="columns[6].visible" />
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true" v-if="columns[7].visible" />
				<el-table-column label="零件组名称" prop="partName" min-width="150" :show-overflow-tooltip="true" v-if="columns[8].visible" />
				<el-table-column label="零件组图号" prop="partFigure" min-width="150" :show-overflow-tooltip="true" v-if="columns[9].visible" />
				<el-table-column label="需求数" prop="partQuantity" min-width="150" :show-overflow-tooltip="true" v-if="columns[10].visible" />
				<el-table-column label="领料原因" prop="replacementSituation" min-width="150" :show-overflow-tooltip="true" v-if="columns[11].visible" />
				<!-- <el-table-column label="接收人" prop="recipientName" min-width="150" :show-overflow-tooltip="true" v-if="columns[12].visible" />
				<el-table-column label="接收日期" prop="recipientTime" min-width="150" :show-overflow-tooltip="true" v-if="columns[13].visible" /> -->
				<el-table-column label="合格证号" prop="certificateNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[12].visible" />
				<el-table-column label="合格接收人" prop="qualifiedName" min-width="150" :show-overflow-tooltip="true" v-if="columns[13].visible" />

				<el-table-column label="操作" class-name="small-padding fixed-width" width="200px" fixed="right" align="center">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildren">
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)" v-hasPermi="['synthesize:store:sinspectlist:annex']">附件</el-button>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleHG(scope.row)" v-hasPermi="['synthesize:store:sinspectlist:HG']">合格证</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex2(scope.row)" v-hasPermi="['synthesize:store:sinspectlist:annex2']">附件</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination65" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改发票对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" class="add-form1" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="接收人" prop="recipientId">
					<el-select v-model="form.recipientId" placeholder="请选择接收人" filterable @change="changeUser">
						<el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="接收日期" prop="recipientTime">
					<el-date-picker v-model="form.recipientTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择接收日期"> </el-date-picker>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { listEntrancelist, listEntrancelistChild, submitIssue } from "@/api/synthesize/store/sinspectlist"
import { mapGetters } from "vuex"
import { getUserList, getcolumn } from "@/api/selectList"

export default {
	name: "Sinspectlist",
	dicts: ["default_approve", "product_intact_state", "inspect_status"],
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			tableTreeRefreshTool: {}, // 用于存储 resolve 方法和展开状态
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 设备保养计划表格数据
			EntrancelistList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				recordNumber: undefined,
				pageNum: 1,
				pageSize: 10,
				deviceName: undefined,
				inspectStatus: undefined,
				applyTime: undefined,
				partName: undefined,
				partFigure: undefined,
				productionBatch: undefined,
				inspectDate: undefined,
				repairNumber: undefined,
				qualifiedName: undefined,
				partRecipientDate: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				recipientId: [{ required: true, message: "请选择接收人", trigger: "blur" }],
				recipientTime: [{ required: true, message: "请选择接收日期", trigger: "blur" }]
			},
			deviceList: [],
			// 更新树刷新
			treeMap: new Map(),
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			// 生产计划
			isOne: false,
			disabled: false,
			// 审批流程
			// openRecords: false,
			approveRecord: [],
			treetablekey: Math.random(),
			// 用户列表
			userList: [],
			// 列信息
			columns: [
				{ key: 0, label: `记录编号`, visible: true },
				{ key: 1, label: `编号`, visible: true },
				{ key: 2, label: `供方`, visible: true },
				{ key: 3, label: `返修任务单`, visible: true },
				{ key: 4, label: `送检时间`, visible: true },
				{ key: 5, label: `工艺通知单`, visible: true },
				{ key: 6, label: `生产批次(3B)`, visible: true },
				{ key: 7, label: `产品型号`, visible: true },
				{ key: 8, label: `零件组名称`, visible: true },
				{ key: 9, label: `零件组图号`, visible: true },
				{ key: 10, label: `需求数`, visible: true },
				{ key: 11, label: `领料原因`, visible: true },
				// { key: 12, label: `接收人`, visible: true },
				// { key: 13, label: `接收日期`, visible: true },
				{ key: 12, label: `合格证号`, visible: true },
				{ key: 13, label: `合格接收人`, visible: true },
				{ key: 14, label: `状态`, visible: true }
			]
		}
	},
	created() {
		this.getSize()
		this.getUserList()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		this.getSize()
		this.getUserList()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination65" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		// 获取用户下拉选
		getUserList() {
			getUserList().then(res => {
				this.userList = res.rows
			})
		},
		//
		changeUser() {
			let cur = this.userList.find(item => {
				return item.userId == this.form.recipientId
			})
			this.form.recipientName = cur.nickName
		},
		/** 查询设备保养计划列表 */
		getList() {
			this.loading = true
			listEntrancelist(this.queryParams).then(response => {
				this.EntrancelistList = response.rows
				this.EntrancelistList.length > 0 &&
					this.EntrancelistList.forEach((item, index) => {
						item.hasChildren = true
						item.sort = index + 1
						// this.$refs.table.toggleRowExpansion(item, false);
					})
				this.total = response.total
				this.loading = false
			})
		},
		refreshLoadTree(parentId) {
			const { tree, treeNode, resolve } = this.treeMap.get(parentId)
			this.loadListDes(tree, treeNode, resolve) // 重新加载子级数据
      this.$refs.table.clearSelection()
		},
		// 关闭所有展开的行
		closeAllExpansions() {
			this.EntrancelistList.forEach(row => {
				this.$refs.table.toggleRowExpansion(row, false)
			})
      this.$refs.table.clearSelection()
      this.getList()
		},
		// 展开/收起时触发
		handleExpandChange(row, expanded) {
			const curr = this.tableTreeRefreshTool[row.id]
			if (!curr) return
			curr.expandCount++
			if (expanded && curr.expandCount > 1 && !curr.prevStatus) {
				listEntrancelistChild({
					id: row.id,
					deviceName: this.queryParams.deviceName,
					inspectStatus: this.queryParams.inspectStatus,
					applyTime: this.queryParams.applyTime,
					partName: this.queryParams.partName,
					partFigure: this.queryParams.partFigure,
					productionBatch: this.queryParams.productionBatch,
					inspectDate: this.queryParams.inspectDate,
					repairNumber: this.queryParams.repairNumber,
					qualifiedName: this.queryParams.qualifiedName
				}).then(res => {
					res.rows.forEach((item, index) => {
						// 父子id会冲突
						item.id = "c" + item.id
						item.sort = index + 1
					})
					curr.resolve(res.rows)
				})
			}
			curr.prevStatus = expanded
		},
		// 获取列表详情
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, { tree: tree, treeNode, resolve })
			}
			this.tableTreeRefreshTool[tree.id] = {
				resolve,
				expandCount: 0, // 展开次数
				prevStatus: false // 上一次的展开状态
			}
			let data = {
				id: tree.id,
				deviceName: this.queryParams.deviceName,
				inspectStatus: this.queryParams.inspectStatus,
				applyTime: this.queryParams.applyTime,
				partName: this.queryParams.partName,
				partFigure: this.queryParams.partFigure,
				productionBatch: this.queryParams.productionBatch,
				inspectDate: this.queryParams.inspectDate,
				repairNumber: this.queryParams.repairNumber,
				qualifiedName: this.queryParams.qualifiedName
			}
			let ret = await listEntrancelistChild(data)
			tree.hasChildren = ret.rows.length > 0
			tree.children = ret.rows

			if (ret.rows.length == 0) {
				resolve([]) // 确保返回空数组
				this.$set(this.$refs.table.store.states.lazyTreeNodeMap, tree.id, [])
			} else {
				ret.rows.forEach((item, index) => {
					item.id = "c" + item.id
					item.sort = index + 1
				})
				resolve(ret.rows)
			}
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				ids: undefined,
				recipientId: undefined,
				recipientName: undefined,
				recipientTime: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.closeAllExpansions()
			this.getList()
			this.treetablekey = Math.random()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
				let flag = this.ids.some(item => item == row.id)
				if (row.hasChildren) {
					row.children.forEach(items => {
						if (flag) {
							this.$refs.table.toggleRowSelection(items, true)
						}
					})
				}
			}
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.table.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.table.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 提交下发 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					submitIssue(this.form).then(response => {
						this.$modal.msgSuccess("操作成功")
						this.open = false
						this.getList()
						this.closeAllExpansions()
						// this.refreshTree()
					})
				}
			})
		},
		handleHG(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.repairMaterialId,
					typeId: 39,
					perm: "synthesize:store:sinspectlist:HG"
				}
			})
		},
		// 附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 41,
					perm: "synthesize:store:sinspectlist:annex"
				}
			})
		},
		handleAnnex2(row) {
			let id = row.id.replace("c", "")
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: id,
					typeId: 42,
					perm: "synthesize:store:sinspectlist:annex2"
				}
			})
		},

		checkIds() {
			// 判断ids
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
			}
			let ids = this.ids.map(item => {
				return item.replace("c", "")
			})
			return ids
		},
		// 更新树
		refreshTree() {
			this.rows = []
			this.ids = []
			// 这个刷新checkbox有问题
			this.treeMap.forEach((item, idx) => {
				this.loadListDes({ id: idx }, item.treeNode, item.resolve)
			})
			// this.treetablekey = Math.random()
		},
		// 下发
		handleDown(row) {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = false
			this.rows.forEach(item => {
				if (item.inspectStatus != "1" && item.inspectStatus != "3" && item.inspectStatus != "5") {
					checkrows = true
				}
			})
			if (checkrows) {
				this.$modal.msg("只有入库、合格、让步接收可以下发")
				return false
			}
			this.reset()
			this.form.ids = ids
			this.open = true
			this.title = "下发"
		}
	}
}
</script>

<style lang="scss" scoped>
// ::v-deep .el-table__fixed-header-wrapper .fixed-width {
// 	width: 122px !important;
// }
</style>
